package com.alan.wifishare.view.impl.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.alan.libapi.model.business.SharedWifiInfo;
import com.alan.libapi.model.business.UserSession;
import com.alan.library.allog.KLog;
import com.alan.wifishare.R;
import com.alan.wifishare.app.GlobalField;
import com.alan.wifishare.app.UserConfig;
import com.alan.wifishare.presenter.MainConnectPS;
import com.alan.wifishare.presenter.wifi.ALNetwork;
import com.alan.wifishare.presenter.wifi.NetworkStateListener;
import com.alan.wifishare.presenter.wifi.NetworkStateObserverManager;
import com.alan.wifishare.utils.BusinessUtil;
import com.alan.wifishare.utils.WifiUtil;
import com.alan.wifishare.view.impl.ActivityJumpUtil;
import com.alan.wifishare.view.iview.IVMainConnectFM;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import java.util.List;

/**
 * @className: MainConnectFragment
 * @describtion: MainConnectFragment
 * @author: AlanWang
 * @email: 850267876@qq.com
 * @time: 2016/4/20 18:24
 */
public class MainConnectFragment extends Fragment implements IVMainConnectFM {

    private static MainConnectPS mainConnectPS;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private boolean isFirstLoc = true;
    private BitmapDescriptor bitmapDescriptorA;
    // 定位相关
    private final int SCAN_SPAN = 100*1000;//重定位时间100秒
    private LocationClient mLocClient;
    public MyLocationListenner myListener;

    public ChangeFragmentListener getChangeFragmentListener() {
        return changeFragmentListener;
    }

    public void setChangeFragmentListener(ChangeFragmentListener changeFragmentListener) {
        this.changeFragmentListener = changeFragmentListener;
    }

    private ChangeFragmentListener changeFragmentListener;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.main_connect_layout, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        bitmapDescriptorA = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
        //test 实际项目中该userSession由登录成后服务器返回并保存为全局变量
//        KLog.e(userSession);
        mainConnectPS = new MainConnectPS(this);
        mainConnectPS.getUserInfo();
        initView();
//        mainConnectPS.refreshNearbyWifiList();//定位成功后才可获取附近的wifi列表
        super.onActivityCreated(savedInstanceState);
    }


    private Button cntRefreshBtn;
//    private Button cntLinkBtn;
    private Button cntConnectBtn;
    private void initView() {
        // TODO: 初始化界面，并在点击连接按钮时执行mainConnectPS.getUserBoundDevice()方法
        BtnOnClickListener btnOnClickListener = new BtnOnClickListener();
        cntRefreshBtn = (Button) getView().findViewById(R.id.cntRefreshBtn);
//        cntLinkBtn = (Button) getView().findViewById(R.id.cntLinkBtn);
        cntConnectBtn = (Button) getView().findViewById(R.id.cntConnectBtn);
        cntRefreshBtn.setOnClickListener(btnOnClickListener);
//        cntLinkBtn.setOnClickListener(btnOnClickListener);
        cntConnectBtn.setOnClickListener(btnOnClickListener);

        initMapView();
        NetworkStateObserverManager.getInstance().registerObserver(new NetworkStateListener() {
            @Override
            public void onStateChanged(int type, int state) {
                KLog.d("type = " + type + "######state = " + state + "######isVisible = " + MainConnectFragment.this.isResumed());
                if(type == ALNetwork.Type.WIFI){
                    
                }else if(type == ALNetwork.Type.CONNECTIVITY){
                    if(state == ALNetwork.State.CONNECTIVITY_CONNECTED){
                        if(MainConnectFragment.this.isResumed()){
                            if(BusinessUtil.isConnectedLink()){
                                if(getChangeFragmentListener() != null){//连接Link成功后执行，写在此处只为测试
                                    getChangeFragmentListener().onFragmentChange(1);
                                }
                            }
                        }

                    }else if(state == ALNetwork.State.CONNECTIVITY_DISCONNECTED){

                    }
                }
            }
        });
    }

    private void initMapView(){
        mMapView = (MapView) getView().findViewById(R.id.bmapView);
        mMapView.showScaleControl(true);
        mMapView.showZoomControls(false);
        //隐藏百度logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.GONE);
        }
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        myListener = new MyLocationListenner();
        mLocClient = new LocationClient(getContext());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(SCAN_SPAN);
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        mLocClient.setLocOption(option);
        mLocClient.start();
    }


    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void toastMsg(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateNearbyWifiListView(List<SharedWifiInfo> wifiInfoList) {
        // TODO: 更新并显示附近的wifi列表
        KLog.e(wifiInfoList);
        mBaiduMap.clear();
        for (SharedWifiInfo sharedWifiInfo : wifiInfoList) {
            // add marker overlay
            LatLng latLng = new LatLng(sharedWifiInfo.getWifiLatitude(), sharedWifiInfo.getWifiLongitude());
            MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptorA).zIndex(9).draggable(true);
            markerOptions.animateType(MarkerOptions.MarkerAnimateType.grow);
            mBaiduMap.addOverlay(markerOptions);
//            Marker mMarkerA = (Marker) (mBaiduMap.addOverlay(markerOptions));
        }
    }

    @Override
    public void gotoBindDeviceView() {
        // TODO: 跳转到设备绑定界面
        ActivityJumpUtil.jump2BindLinkScanAct(getActivity());
    }

    @Override
    public void gotoBuyPackageView() {
        // TODO: 跳转到套餐购买界面 
    }

    @Override
    public void gotoConnectDeviceView() {
        KLog.e(GlobalField.userConfig.getDeviceSSID());
        if(GlobalField.userConfig.getDeviceSSID() == null){
            // TODO: 跳转到设备连接界面
            ActivityJumpUtil.jump2ConnectLinkAct(getActivity());
        } else {//如果已经连接过wifi则从保存的本地数据中获取要连接的wifi并自动连接
            if(BusinessUtil.isConnectedLink()){//如果已经连接上设备
                KLog.e();
                if(getChangeFragmentListener() != null){
                    KLog.e();
                    getChangeFragmentListener().onFragmentChange(1);
                }
            }else {
                if(!GlobalField.wifiUtil.isWifiEnabled()){
                    GlobalField.wifiUtil.openWifi();
                }
                GlobalField.wifiUtil.connectToWifi(GlobalField.userConfig.getDeviceSSID(),
                        GlobalField.userConfig.getDevicePwd(), WifiUtil.TYPE_WPA);
            }
        }
    }

    @Override
    public void getAreaIdSuccess(int areaId) {
        GlobalField.userLocation.setAreaId(areaId);
        mainConnectPS.refreshNearbyWifiList(areaId, GlobalField.userLocation.getLongitude(), GlobalField.userLocation.getLatitude());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ActivityJumpUtil.RequestCode.CNT_MAIN_2_CONNECT
                && resultCode == ActivityJumpUtil.ResultCode.CNT_CONNECT_LINK_2_CNT_MAIN){
            if(getChangeFragmentListener() != null){//连接Link成功后执行，写在此处只为测试
                getChangeFragmentListener().onFragmentChange(1);
            }
        }
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mBaiduMap = null;
        mMapView.onDestroy();
        mMapView = null;
        if(bitmapDescriptorA != null){
            bitmapDescriptorA.recycle();
            bitmapDescriptorA = null;
        }
        mainConnectPS = null;
        super.onDestroy();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            KLog.d("getLatitude = " + location.getLatitude() + "<<---->>getLongitude = " + location.getLongitude());
            KLog.e("getCity = " + location.getCity() + "<<---->>getCityCode = " + location.getCityCode()
                    + "<<---->>getCountryCode = " + location.getCountryCode()
                    + "<<---->>getCountry = " + location.getCountry()
                    + "<<---->>getProvince = " + location.getProvince()
                    + "<<---->>getCity = " + location.getCity()
                    + "<<---->>getCityCode = " + location.getCityCode()
                    + "<<---->>getDistrict = " + location.getDistrict()
                    + "<<---->>getStreet = " + location.getStreet()
                    + "<<---->>getStreetNumber = " + location.getStreetNumber()
                    + "<<---->>getLocationDescribe = " + location.getLocationDescribe()
                    + "<<---->>getAddrStr = " + location.getAddrStr()
                    + "<<---->>getAddress = " + location.getAddress());

            GlobalField.userLocation.setCountry(location.getCountry());
            GlobalField.userLocation.setProvince(location.getProvince());
            GlobalField.userLocation.setCity(location.getCity());
            GlobalField.userLocation.setDistrict(location.getDistrict());
            GlobalField.userLocation.setLongitude(location.getLongitude());
            GlobalField.userLocation.setLatitude(location.getLatitude());
            GlobalField.userLocation.setAddressStr(location.getAddrStr());
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                mainConnectPS.getAreaIdByAddress(GlobalField.userLocation.getCountry(), GlobalField.userLocation.getProvince(),
                        GlobalField.userLocation.getCity(), GlobalField.userLocation.getDistrict());
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
//                initOverlay();
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    class BtnOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.cntRefreshBtn: //刷新附近wifi列表按钮
                    toastMsg("刷新");
                    KLog.e(GlobalField.wifiUtil.getWifiInfo());
                    KLog.e(GlobalField.wifiUtil.getWifiInfo().getSSID());
                    if(GlobalField.userLocation.getAreaId() > 0){
                        mainConnectPS.refreshNearbyWifiList(GlobalField.userLocation.getAreaId(),
                                GlobalField.userLocation.getLongitude(), GlobalField.userLocation.getLatitude());
                    }else {
                        toastMsg("正在获取当前位置，请稍后！");
                    }
                    break;
//                case R.id.cntLinkBtn: //连接Link管理界面
//                    if(BusinessUtil.isConnectedLink()){
//                        ActivityJumpUtil.jump2LinkManageAct(getActivity(), GlobalField.wifiUtil.getWifiInfo().getSSID());
//                    }
//                    break;
                case R.id.cntConnectBtn: //进入连接界面
                    // TODO: Alan 判断是否符合连接情况（是否绑定设备，是否在付费试用期内）
                    mainConnectPS.getUserBoundDevice();
//                    ActivityJumpUtil.jump2ConnectLinkAct(getActivity());//test
                    break;
                default:
                    break;
            }
        }
    }
}
